package com.euq.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Random;

public class MD5 {
    public static String generateSalt() {
        int length = 5;
        Random random = new Random();
        byte[] salt = new byte[length];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt); // 使用Base64编码盐值，便于存储
    }

    // 使用MD5加盐加密密码
    public static String md5(String password, String salt) throws NoSuchAlgorithmException {
        // 拼接密码和盐值
        String saltedPassword = salt + password;

        // 获取MD5摘要实例
        MessageDigest md = MessageDigest.getInstance("MD5");

        // 获取加密后的字节数组
        byte[] hashedBytes = md.digest(saltedPassword.getBytes());

        // 转为16进制的字符串表示
        StringBuilder hexString = new StringBuilder();
        for (byte b : hashedBytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString();
    }

}